<template>
  <div id="chat-div">
    <el-row :class="{'selectedUserId-el-row':selectedUserId}">
      <el-col>{{selectedUserId}}</el-col>
    </el-row>

    <el-row id="chatBox-content">
      <el-col>
        <div id="messages">
          <div
            v-for="(messageInfo,i) in messageInfos"
            :key="i"
            :class="[messageInfo.oneself?'message-right':'message-left']"
          >
            <div
              class="fromUserDiv"
              :style="{'pull-right':messageInfo.oneself}"
            >{{messageInfo.fromUserId}},{{messageInfo.sendTime}}</div>
            <div class="message-span" v-show="messageInfo.type=='file'">
              <div v-if="messageInfo.specificTypes == 'image/jpeg'">
                <a :href="messageInfo.fileUrl" target="_blank" :download="messageInfo.message">
                  <img :src="messageInfo.fileUrl" width="100" height="80" />
                </a>
              </div>
              <div v-if="messageInfo.specificTypes != 'image/jpeg'">
                <a :href="messageInfo.fileUrl">{{messageInfo.message}}</a>
              </div>
            </div>
            <div class="message-span" v-show="messageInfo.type!='file'">{{messageInfo.message}}</div>
          </div>
        </div>
      </el-col>
    </el-row>

    <el-row id="send-row" v-show="selectedUserId">
      <el-col :span="24" class="tools-col">
        <el-upload
          action="#"
          list-type="picture"
          ref="upload"
          :limit="5"
          :show-file-list="true"
          :http-request="selectFile"
          :on-remove="handleRemoveFile"
        >
          <i class="el-icon-picture-outline" slot="trigger"></i>
        </el-upload>
      </el-col>
      <el-col :span="22">
        <el-input type="textarea" :rows="4" placeholder="请输入内容" @keyup.enter.native="sendMsg" v-model="message"></el-input>
      </el-col>
      <el-col :span="2">
        <el-button type="primary" @click="sendAllMessage" :disabled="!selectedUserId" plain>Send</el-button>
      </el-col>
    </el-row>
  </div>
</template>
<script>
import { mapState } from "vuex";
import { EventBus } from "../components/event-bus.js";
import io from "socket.io-client";
var socket = io.connect("http://192.168.3.215:8888");
export default {
  data() {
    return {
      message: "",
      messageInfos: [],
      selectedUserId: "",
      fileList: []
    };
  },
  computed: {
    ...mapState({ user: state => state.user })
  },
  mounted() {
    var _this = this;
    //选择联系人
    EventBus.$on("change-contact", function(selectedUserId) {
      if (selectedUserId == _this.selectedUserId) {
        return;
      }
      _this.selectedUserId = selectedUserId;
      _this.messageInfos = [];
    });
  },
  updated() {
    //this.scrollToBottom();
  },
  methods: {
    sendAllMessage(){
      this.sendMsg();
      this.sendFiles();
    },
    sendMsg() {
      if (!this.message) {
        return;
      }
      var sendTime = this.$moment().format("YYYY MMMM Do, h:mm:ss a");
      var messageInfo = {
        fromUserId: this.user.userId,
        toUserId: this.selectedUserId,
        message: this.message,
        sendTime: sendTime
      };
      socket.emit("clientMessage", JSON.stringify(messageInfo));
      messageInfo.oneself = 1;
      this.messageInfos.push(messageInfo);
      this.message = "";
      this.scrollToBottom();
    },

    selectFile(fileObj) {
      this.fileList.push(fileObj.file);
      this.scrollToBottom();
    },
    handleRemoveFile(file) {
      var uid = file.uid;
      var index = 0;
      for (var i = 0; i < this.fileList.length; i++) {
        if (this.fileList[i].uid == uid) {
          index = i;
          break;
        }
      }
      this.fileList.splice(index, 1);
      this.scrollToBottom();
    },
    sendFiles() {
      if(this.fileList == []){
        return;
      }
      for (var i = 0; i < this.fileList.length; i++) {
        var fileData = this.fileList[i];
        var sendTime = this.$moment().format("YYYY MMMM Do, h:mm:ss a");
        var messageInfo = {
          fromUserId: this.user.userId,
          toUserId: this.selectedUserId,
          message: fileData.name,
          type: "file",
          specificTypes: fileData.type,
          sendTime: sendTime
        };
        socket.emit("file", JSON.stringify(messageInfo), fileData);
      }
      this.$refs.upload.clearFiles();
      this.fileList = [];
    },
    //控制滚动条到底部
    scrollToBottom: function() {
      this.$nextTick(() => {
        var container = this.$el.querySelector("#chatBox-content");
        container.scrollTop = container.scrollHeight;
      });
    }
  },
  created() {
    var _this = this;
    //收到消息
    socket.on(this.user.userId, function(data) {
      var messageInfo = JSON.parse(data);
      //文件上传成功后，服务器发给发送方的
      if (messageInfo.fromUserId == _this.user.userId) {
        messageInfo.oneself = 1;
      } else {
        messageInfo.oneself = 0;
        _this.selectedUserId = messageInfo.fromUserId;
        EventBus.$emit("news", messageInfo.fromUserId);
      }
      _this.messageInfos.push(messageInfo);
      _this.scrollToBottom();
    });
  }
};
</script>
<style scoped>
#chat-div {
  height: 100%;
}
.selectedUserId-el-row {
  border-bottom: 1px solid#DCDFE6;
  font-size: 18px;
  font-weight: bold;
  padding: 15px;
}
#chatBox-content {
  height: 500px;
  overflow-y: auto;
  padding-left: 10px;
  padding-right: 10px;
}
#send-row {
  height: 50px;
  text-align: right;
  padding-left: 15px;
  padding-right: 15px;
  border-top: 1px solid #dcdfe6;
}
.message-right {
  margin-top: 10px;
  text-align: right;
}
.message-left {
  margin-top: 10px;
  text-align: left;
}
.fromUserDiv {
  font-size: 12px;
  color: rgb(179, 216, 255);
  padding-left: 10px;
  padding-right: 10px;
}
.message-span {
  width: auto;
  height: auto;
  padding: 20px;
  border: 1px solid #e7e8ec;
  font-size: 13px;
  color: #303133;
  margin-top: 5px;
  margin-bottom: 5px;
}
.tools-col {
  text-align: left;
  margin:10px;
}
</style>



